package com.alan.weather.service.impl;

import com.alan.weather.common.responseResult.R;
import com.alan.weather.entity.Employee;
import com.alan.weather.mapper.EmployeeMapper;
import com.alan.weather.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 员工信息(Employee)表服务实现类
 *
 * @author makejava
 * @since 2022-12-25 15:33:22
 */
@Slf4j
@Service("employeeService")
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    /*
        登录
     */
    @Override
    public R login(Employee employee, HttpServletRequest request) {

        // 1.获取密码并加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 2.查询用户
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = getOne(queryWrapper);
        // 3.校验用户名是否存在
        if(ObjectUtils.isEmpty(one)){
            return R.error("用户不存在！");
        }
        // 4.校验密码正确性
        if (!password.equals(one.getPassword())){
            return R.error("密码错误！");
        }
        // 5.确认账号状态
        if (one.getStatus() == 0) {return R.error("账号已禁用！");}
        request.getSession().setAttribute("employee", one.getId());
        return R.success(one);
    }

    @Override
    public R addEmployee(Employee employee,HttpServletRequest request) {
        // 这里貌似只能手动添加了
        Long id = (Long)request.getSession().getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);

        //设置初始密码123456
        String pass = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(pass);

        save(employee);
        return R.success("添加员工成功！");
    }

    @Override
    public R<Page> listEmp(int page, int pageSize, String userName) {


        // 条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(userName),Employee::getUsername,userName);

        // 分页构造器
        Page p = new Page<>(page,pageSize);

        // 执行查询
        page(p,queryWrapper);

        List records = p.getRecords();

        return R.success(p);
    }

    @Override
    public R updateStatus(Employee employee,HttpServletRequest request) {
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        updateById(employee);
        return R.success("账号状态更新成功！");
    }
}

